package basic.nio;

import org.junit.Test;

import java.nio.ByteBuffer;

public class ByteBufferTest {


    @Test
    public void  testBuffer(){
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        ByteBuffer dorectBuffer = ByteBuffer.allocateDirect(1024);
        System.out.println(byteBuffer.isDirect());
        System.out.println(dorectBuffer.isDirect());
    }

    @Test
    public void testAPI1(){

        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byte[] bys = "111".getBytes();
        byteBuffer.putInt(1);
        byteBuffer.putInt(2);
        System.out.println("remain:"+byteBuffer.remaining());
        System.out.println("end");
        System.out.println("old limit:"+byteBuffer.limit());
        byteBuffer.limit(9);
        System.out.println("new limit:"+byteBuffer.limit());
        System.out.println("position:"+byteBuffer.position());
        byteBuffer.flip();
        System.out.println(byteBuffer.getInt());
        System.out.println(byteBuffer.getInt());
        System.out.println("remain:"+byteBuffer.remaining());

    }

    @Test
    public void testRemain(){
        ByteBuffer byteBuffer = ByteBuffer.allocate(20);
        byteBuffer.putInt(1);
        System.out.println("remain:"+byteBuffer.remaining());
        byteBuffer.putInt(2);
        System.out.println("remain:"+byteBuffer.remaining());
        byteBuffer.flip();
        System.out.println(byteBuffer.getInt());
        System.out.println(byteBuffer.getInt());
        System.out.println("remain:"+byteBuffer.remaining());
        System.out.println("remain:"+byteBuffer.remaining());
    }

    @Test
    public void testBuffer2(){
        ByteBuffer byteBuffer = ByteBuffer.allocate(20);
        byteBuffer.putInt(256);
        byteBuffer.putInt(255);
        byte a = 20;
        byteBuffer.put(a);
        System.out.println(byteBuffer.remaining());
    }

    @Test
    public void testSplit(){
        int a = 1888022145;
        System.out.println(Integer.toBinaryString(a));
        byte[] bytes = new byte[4];
        bytes[3] = (byte) (a >>24);
        bytes[2] = (byte) (a >>16);
        bytes[1] = (byte)(a >>8);
        bytes[0] = (byte)a;
        for (int i=0;i<bytes.length;i++){
            System.out.println(bytes[i]);
        }
        ByteBuffer byteBuffer = ByteBuffer.allocate(20);
        byteBuffer.putInt(a);
        System.out.println("do....");
    }
}
